package netty.ProtoBuf.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @ClassName ClientHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/1/20 13:25
 * @Version 1.0
 **/
public class ClientHandler extends ChannelInboundHandlerAdapter {


    //通道 准备好了 就会触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //发送Student对象
//        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("豹子头林冲").build();
        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("智多星").build();
        ctx.writeAndFlush(student);

    }

    //读取客户端发送的消息
    //通道有读取事件 ---  就会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf)msg;

        System.out.println("服务器回复消息："+ byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器地址："+ctx.channel().remoteAddress());
    }


    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();;
        ctx.close();

    }
}
